package com.maxd.error;

import com.google.common.collect.Lists;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@ControllerAdvice
public class ExceptionHandle {

    private final static Logger LOGGER = LoggerFactory.getLogger(ExceptionHandle.class);
    private static Pattern p = Pattern.compile("[\u4e00-\u9fa5]");
    /**
     * 判断错误是否是已定义的已知错误，不是则由未知错误代替，同时记录在log中
     *
     * @param e
     * @return
     */
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public Result exceptionGet(Exception e) {

        LOGGER.info("exception class is : {}", e.getClass().getName());

        if (e instanceof DescribeException) {
            DescribeException de = (DescribeException) e;
            LOGGER.info("发生业务异常，返回码:{}, 返回信息:{}", de.getCode(), de.getMessage());
            LOGGER.error("异常堆栈", de);
            return ResultUtil.error(de.getCode(), de.getMessage());
        }

        if(e instanceof MethodArgumentNotValidException) {
            return getResult((MethodArgumentNotValidException) e);
        }

        if ("用户信息失效,请重新登录".equals(e.getMessage())) {
            return ResultUtil.error(ExceptionEnum.WRONT_TOKEN);
        }
        LOGGER.error("发现异常.", e);
        //判断异常类型是否包含中文 如果包含 则代表是代码中定义的错误 直接返回
        String s = e.getMessage();
        Matcher m = p.matcher(s);
        if(m.find()) {
            return ResultUtil.error(-200,e.getMessage());
        }
        return ResultUtil.error(ExceptionEnum.UNKNOW_ERROR);
    }

    private Result getResult(MethodArgumentNotValidException ae) {
        List<FieldError> fieldErrors = ae.getFieldErrors();
        List<String> msgList = Lists.newArrayList();
        for (FieldError fieldError : fieldErrors) {
            msgList.add(fieldError.getDefaultMessage());
        }
        return ResultUtil.error(-200, StringUtils.join(msgList, ";"));
    }
}
